<?php

class CategoryService {

	/**
	 * 获得全部栏目名、栏目id、模型名和栏目id
	 * @return [array]    arr     [全部栏目名、栏目id、模型名和栏目id]
	 */
	public static function index(){
		$categories = Category::all();
		if(!isset($categories)){
			return CMSException::$noCategoryErr;
		}
		$categoryArray = array();
		for($i=0; $i<count($categories); $i++){
			$model = Model::find($categories[$i]['model_id']);
			if(!isset($model)){
				return CMSException::$noModelErr;
			}
			$categoryArray[$i]['categoryId']        = $categories[$i]['id'];
			$categoryArray[$i]['categoryName']      = $categories[$i]['category_name'];
			$categoryArray[$i]['modelId']           = $model['id'];
			$categoryArray[$i]['modelName']         = $model['model_name'];
		}
		return $categoryArray;
	}

	/**
	 * 增加栏目
	 * @param [string] $categoryName 	栏目名
	 * @param [int] $modelId     		所用模型id
	 */
	public static function add($categoryName, $modelId){
		try{
			DB::transaction(function() use ($categoryName, $modelId){
				$category = new Category;
				$category->category_name = $categoryName;
				$category->model_Id = $modelId;
				$category->save();
			});
		}catch(Exception $e){
			return CMSException::$addCategoryErr;
		}
		return CMSException::$ok;
	}

	/**
	 * 更新栏目
	 * @param  [array] $category [栏目id，栏目名，栏目所用模型id]
	 * @return [array]       [异常信息]
	 */
	public static function update($category){
		try{
			DB::transaction(function() use ($category){
				$categoryUpdate = Category::find($category['id']);
				
				if(!isset($categoryUpdate)){
					return Response::json(CMSException::$noCategoryErr);
				}
				$categoryUpdate->category_name = $category['categoryName'];
				$categoryUpdate->model_Id      = $category['modelId'];
				$categoryUpdate->save();
			});
		}catch(Exception $e){
			return CMSException::$updateCategoryErr;
		}
		return CMSException::$ok;
	}

	/**
	 * 删除栏目
	 * @param  [int] $categoryId [栏目id]
	 * @return [array]             [异常信息]
	 */
	public static function delete($categoryId){
		try{
			$category = Category::find($categoryId);
			if(!isset($category)){
				return CMSException::$noCategoryErr;
			}
			$modelName = Model::where('id', $category['model_id'])->pluck('table_name');
			if(!isset($modelName)){
				return CMSException::$noModelErr;
			}
			$model     = studly_case($modelName);
			$documents = $model::where('category_id', $categoryId)->delete();
			$category->delete();
		}catch(Exception $e){
			return CMSException::$deleteCategoryErr;
		}
		return CMSException::$ok;
	}

}